from PyQt5.QtWidgets import QWidget, QFileDialog, QMessageBox
import os

# 导入窗体内容
from design.uploadDlg import *

from common.logger import logger
from common.retcode import RetCode, TransferType
from common.types import TransferInfo
from common.utils import get_file_name, center_window_on_screen

# 创建 MainWin 类并传入Ui_MainWindow
class UploadDlg(QWidget, Ui_UploadDlg):
	def __init__(self, transfer_table, parent=None):
		super(UploadDlg, self).__init__(parent)
		self.setupUi(self)
		center_window_on_screen(self)

		self.pushButtonUploadSel.clicked.connect(self.onClickedUploadSel)
		self.pushButtonOk.clicked.connect(self.onClickedOk)
		self.radioButtonDir.clicked.connect(self.onClickedRadioButtonDir)
		self.radioButtonFiles.clicked.connect(self.onClickedRadioButtonFiles)

		self._fid = -11
		self._last_path = ""
		self._last_sel_type = 0 # 0: 选择文件夹；1：选择文件
		self._transfer_table = transfer_table

	def reset(self, fid):
		self._fid = fid
		self.lineEditUpload.setText(self.getLastPathDisplay())

	def getLastPathDisplay(self):
		if self._last_sel_type == 0:
			return self._last_path
		else:
			return ';'.join(self._last_path)

	def onClickedUploadSel(self):
		cur_path = ""
		if self._last_sel_type == 0:
			cur_path = self._last_path
		else:
			if self._last_path is None or len(self._last_path) == 0:
				cur_path = ""
			else:
				cur_path = self._last_path[0]

		if self.radioButtonDir.isChecked():
			self._last_path = QFileDialog.getExistingDirectory(self, '选取上传文件', cur_path)
			self._last_sel_type = 0
		else:
			self._last_path, _ = QFileDialog.getOpenFileNames(self, '选取上传文件', cur_path, "All Files (*)")
			self._last_sel_type = 1
		print(self._last_path)
		self.lineEditUpload.setText(self.getLastPathDisplay())

	def onClickedOk(self):
		transfer_info = TransferInfo()
		transfer_info.fid = self._fid
		transfer_info.type = TransferType.UPLOAD
		transfer_info.isFolder = True
		transfer_info.force = self.checkBoxForce.isChecked()
		transfer_info.mkdir = self.checkBoxMkdir.isChecked()
		transfer_info.check = self.checkBoxCheck.isChecked()
		transfer_info._upload_type = self._last_sel_type

		if self._last_sel_type == 0:
			transfer_info.path = self._last_path
			transfer_info.name = get_file_name(transfer_info.path)
		else:
			transfer_info.path = os.path.dirname(self._last_path[0])
			transfer_info._upload_files = self._last_path
			if len(transfer_info._upload_files) == 1:
				transfer_info.isFolder = False
				transfer_info.name = get_file_name(self._last_path[0])
			else:
				transfer_info.name = get_file_name(transfer_info.path)

		self._transfer_table.add_upload_task(transfer_info)
		self.hide()

	def onClickedRadioButtonDir(self):
		self.checkBoxMkdir.setChecked(True)

	def onClickedRadioButtonFiles(self):
		self.checkBoxMkdir.setChecked(False)
		